<?php
include 'include/function.php';
$database = connect_database();
$res = mysql_query("select judge_id from judges where state='free'") or die("query error");
$row = mysql_fetch_row($res);
if (empty ($row)) {
    echo "Too many judges\n";
    exit;
}
$judge_id = $row[0];
$res = mysql_query("update judges set state='used' where judge_id='$judge_id'") or die("query error");
echo "Select judge_id: $judge_id\n";

while (true) {
    sleep(1);
    $res = mysql_query("select state from judges where judge_id='$judge_id'") or die("query error");
    $row = mysql_fetch_row($res);
    if ($row[0] == "stop") {
        echo "Judge stopping...\n";
        $res = mysql_query("update judges set state='free' where judge_id='$judge_id'") or die("query error");
        echo "Stopped.\n";
        break;
    }
    
    $res = mysql_query("select run_id, code, language, uva_problem_id from runs, problems where runs.problem_id=problems.problem_id and result='Waiting'", $database) or die("query error");
    $row = mysql_fetch_row($res);
    if (empty($row))
        continue;
    $run_id = $row[0];
    $code = $row[1];
    $language = $row[2];
    $uva_problem_id = $row[3];
    echo "Judge_id: $judge_id\n";
    echo "Judging $run_id\n";
    $res = mysql_query("update runs set result = 'Judging' where run_id='$run_id'", $database) or die("query error");
    
    /*
    sleep(1);
    $tmp = rand(0, 3);
    if ($tmp == 0)
        $result = "Accepted";
    else if ($tmp == 1)
        $result = "Wrong Answer";
    else if ($tmp == 2)
        $result = "Time Limit Exceeded";
    else if ($tmp == 3)
        $result = "Runtime Error";
    */
    
    file_put_contents("$judge_id.txt", $code);
    
    echo file_get_contents("$judge_id.txt");
    
    sleep(1);
    
    $cmd = "java uvaSubmit $judge_id $uva_problem_id $language < $judge_id.txt";
    
    echo "excute:\n";
    echo $cmd;
    
    $result = system($cmd);
    
    
    $res = mysql_query("update runs set result = '$result' where run_id='$run_id'", $database) or die("query error");
    echo "Result: $result\n\n";
}
?>
